package edu.jamestang.yeb.config;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.impl.AMQImpl;
import edu.jamestang.yeb.entity.MailConstants;
import edu.jamestang.yeb.entity.MailLog;
import edu.jamestang.yeb.service.MailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/**
 * @author JamesTang
 * @date 2021/12/28 22:55
 */
@Configuration
@Slf4j
public class RabbitConfig {

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private MailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate(){

        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);

        /*
         * Message confirm callback,confirm message trans to broker
         * data: Message UUID
         * ack: Confirm result
         * cause: Failure reason
         */
        rabbitTemplate.setConfirmCallback((data, ack, cause)->{

            String msgId = null;
            if (data != null) {
                msgId = data.getId();
            }
            if(ack){
                log.info("{}======>Message send complete",msgId);
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",1).eq("msgId",msgId));
            }else {
                log.error("{}======>Message send failure",msgId);
            }
        });


        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingKey)->{
            log.error("{}======>Message send failure",msg.getBody());
        });

        return rabbitTemplate;
    }



    @Bean
    public Queue queue(){
        return new Queue(MailConstants.MAIL_QUEUE_NAME);
    }

    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange(MailConstants.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.MAIL_ROUTING_KEY_NAME);
    }
}
